package com.jhgsys.internal.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.workflow.constant.WorkflowConstant;
import com.jhgsys.internal.common.context.BeanContext;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.common.utils.SpringContextUtil;
import com.jhgsys.internal.system.entity.Role;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.IRoleService;
import com.jhgsys.internal.system.service.IUserRoleService;
import com.jhgsys.internal.system.service.IUserService;
import com.jhgsys.internal.workflow.callbackTask.base.BaseWorkflowConditionEvent;
import com.jhgsys.internal.workflow.callbackTask.base.BaseWorkflowNodeEvent;
import com.jhgsys.internal.workflow.callbackTask.base.BaseWorkflowNotifierEvent;
import com.jhgsys.internal.workflow.callbackTask.base.BaseWorkflowReviewEvent;
import com.jhgsys.internal.workflow.entity.*;
import com.jhgsys.internal.workflow.mapper.WorkflowNodeMapper;
import com.jhgsys.internal.workflow.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 流程节点表 Service实现
 *
 * @author fenghaijun
 * @date 2024-07-19 08:55:30
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class WorkflowNodeServiceImpl extends ServiceImpl<WorkflowNodeMapper, WorkflowNode> implements IWorkflowNodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IWorkflowNodeTransService workflowNodeTransService;

    @Autowired
    private IWorkflowNodeReviewService workflowNodeReviewService;

    @Autowired
    private IWorkflowNodeTransConditionService workflowNodeTransConditionService;

    @Autowired
    private IWorkflowNodeButtonService workflowNodeButtonService;

    @Autowired
    private IWorkflowApplyReviewLogService workflowApplyReviewLogService;

    @Resource
    private WorkflowNodeMapper workflowNodeMapper;

    /**
     * 查询（分页）
     *
     * @param request      QueryRequest
     * @param workflowNode workflowNode
     * @return IPage<WorkflowNode>
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    public IPage<WorkflowNode> findWorkflowNodes(QueryRequest request, WorkflowNode workflowNode) {
        LambdaQueryWrapper<WorkflowNode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkflowNode::getDeletedFlg, FebsConstant.VALID);
        // TODO 设置查询条件

        Page<WorkflowNode> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询（所有）
     *
     * @param workflowNode workflowNode
     * @return List<WorkflowNode>
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    public List<WorkflowNode> findWorkflowNodes(WorkflowNode workflowNode) {
        LambdaQueryWrapper<WorkflowNode> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(workflowNode.getDeletedFlg())) {
            queryWrapper.eq(WorkflowNode::getDeletedFlg, workflowNode.getDeletedFlg());
        }
        if (null != workflowNode.getWorkflowNodeUuid()) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeUuid, workflowNode.getWorkflowNodeUuid());
        }
        if (null != workflowNode.getWorkflowId()) {
            queryWrapper.eq(WorkflowNode::getWorkflowId, workflowNode.getWorkflowId());
        }
        if (StringUtils.isNotBlank(workflowNode.getWorkflowNodeType())) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeType, workflowNode.getWorkflowNodeType());
        }
        if (StringUtils.isNotBlank(workflowNode.getWorkflowNodeCheckType())) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeCheckType, workflowNode.getWorkflowNodeCheckType());
        }
        if (StringUtils.isNotBlank(workflowNode.getNodeModifyFlg())) {
            queryWrapper.eq(WorkflowNode::getNodeModifyFlg, workflowNode.getNodeModifyFlg());
        }
        if (StringUtils.isNotBlank(workflowNode.getNodeBeforeReviewFlg())) {
            queryWrapper.eq(WorkflowNode::getNodeModifyFlg, workflowNode.getNodeBeforeReviewFlg());
        }
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据条件查询
     *
     * @param workflowNode workflowNode
     * @return WorkflowNode
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    public WorkflowNode findWorkflowNode(WorkflowNode workflowNode) {
        LambdaQueryWrapper<WorkflowNode> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(workflowNode.getDeletedFlg())) {
            queryWrapper.eq(WorkflowNode::getDeletedFlg, workflowNode.getDeletedFlg());
        }
        if (null != workflowNode.getWorkflowNodeUuid()) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeUuid, workflowNode.getWorkflowNodeUuid());
        }
        if (null != workflowNode.getWorkflowId()) {
            queryWrapper.eq(WorkflowNode::getWorkflowId, workflowNode.getWorkflowId());
        }
        if (StringUtils.isNotBlank(workflowNode.getWorkflowNodeType())) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeType, workflowNode.getWorkflowNodeType());
        }
        if (StringUtils.isNotBlank(workflowNode.getWorkflowNodeCheckType())) {
            queryWrapper.eq(WorkflowNode::getWorkflowNodeCheckType, workflowNode.getWorkflowNodeCheckType());
        }
        if (StringUtils.isNotBlank(workflowNode.getNodeModifyFlg())) {
            queryWrapper.eq(WorkflowNode::getNodeModifyFlg, workflowNode.getNodeModifyFlg());
        }
        if (StringUtils.isNotBlank(workflowNode.getNodeBeforeReviewFlg())) {
            queryWrapper.eq(WorkflowNode::getNodeModifyFlg, workflowNode.getNodeBeforeReviewFlg());
        }
        queryWrapper.last(" LIMIT 1");
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return WorkflowNode
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    public WorkflowNode findWorkflowNodeById(String id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     *
     * @param workflowNode workflowNode
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    @Transactional
    public void createWorkflowNode(WorkflowNode workflowNode) {
        workflowNode.setCreatedTime(new Date());
        this.save(workflowNode);
    }

    /**
     * 修改
     *
     * @param workflowNode workflowNode
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    @Transactional
    public void updateWorkflowNode(WorkflowNode workflowNode) {
        workflowNode.setUpdatedTime(new Date());
        this.saveOrUpdate(workflowNode);
    }

    /**
     * 逻辑删除
     *
     * @param workflowNode    workflowNode
     * @param workflowNodeIds workflowNodeIds
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    @Transactional
    public void deleteWorkflowNode(WorkflowNode workflowNode, String workflowNodeIds) {
        List<String> list = Arrays.asList(workflowNodeIds.split(StringPool.COMMA));
        this.baseMapper.update(workflowNode, new LambdaQueryWrapper<WorkflowNode>().in(WorkflowNode::getWorkflowNodeId, list));
    }

    /**
     * 物理删除
     *
     * @param workflowNodeIds workflowNodeIds
     * @author fenghaijun
     * @date 2024-07-19 08:55:30
     */
    @Override
    @Transactional
    public void physicallyDeleteWorkflowNode(String workflowNodeIds) {
        List<String> list = Arrays.asList(workflowNodeIds.split(StringPool.COMMA));
        LambdaQueryWrapper<WorkflowNode> wapper = new LambdaQueryWrapper<>();
        wapper.in(WorkflowNode::getWorkflowNodeId, list);
        this.remove(wapper);
    }


    /**
     * 流程自定义实现类
     *
     * @param classType classType 1: 自定义审核权限实现 2:自定义节点执行事件实现 3:自定义抄送实现 4：自定义条件事件实现
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @Override
    public String[] queryWorkflowCustomBean(String classType) {

        String[] beanNameList = null;
        switch (classType) {
            case "1":
                beanNameList = BeanContext.getBeanNamesForType(BaseWorkflowReviewEvent.class);
                break;
            case "2":
                beanNameList = BeanContext.getBeanNamesForType(BaseWorkflowNodeEvent.class);
                break;
            case "3":
                beanNameList = BeanContext.getBeanNamesForType(BaseWorkflowNotifierEvent.class);
                break;
            case "4":
                beanNameList = BeanContext.getBeanNamesForType(BaseWorkflowConditionEvent.class);
                break;
        }
        return beanNameList;
    }

    /**
     * 获取流程开始节点
     *
     * @param workflowId
     * @param workflowId
     * @return
     */
    @Override
    public WorkflowNode getStartNode(String workflowId) {
        WorkflowNode parDesignNode = new WorkflowNode();
        parDesignNode.setWorkflowId(workflowId);
        parDesignNode.setWorkflowNodeType(WorkflowConstant.START_NODE);
        parDesignNode.setDeletedFlg("0");
        WorkflowNode startNode = findWorkflowNode(parDesignNode);
        return startNode;
    }

    /**
     * 根据当前节点获取下一节点
     *
     * @param currentNode       当前节点
     * @param customizeBtnId    当前节点操作的按钮Id
     * @param workflowApply     业务申请
     * @param isSaveWorkflowLog 是否保存流程日志
     * @return
     */
    @Override
    @Transactional
    public WorkflowNode getNextNode(WorkflowNode currentNode, String customizeBtnId, WorkflowApply workflowApply, boolean isSaveWorkflowLog) throws FebsException {

        WorkflowNode nextNode = new WorkflowNode();
        String workflowApplyId = workflowApply.getWorkflowApplyId();
        String tenantId = workflowApply.getTenantId();
        String workflowId = workflowApply.getWorkflowId();
        String createBy = workflowApply.getCreatedBy();

        //#region 根据起始节点获取所有流向
        WorkflowNodeTrans parNodeTrans = new WorkflowNodeTrans();
        parNodeTrans = new WorkflowNodeTrans();
        parNodeTrans.setTenantId(tenantId);
        parNodeTrans.setWorkflowId(workflowId);
        parNodeTrans.setWorkflowNodeFromId(currentNode.getWorkflowNodeId());
        List<WorkflowNodeTrans> currentNodeTranList = workflowNodeTransService.findWorkflowNodeTranss(parNodeTrans);
        //#endregion

        //#region遍历所有流向
        if (null != currentNodeTranList && currentNodeTranList.size() > 0) {
            if (currentNodeTranList.size() > 1 && WorkflowConstant.ROUTE_NODE.equals(currentNode.getWorkflowNodeType())) {
                nextNode = workflowConditionCompare(workflowApplyId, currentNodeTranList, createBy, customizeBtnId);
            } else {
                //正常节点流向
                WorkflowNodeTrans currentNodeTrans = currentNodeTranList.get(0);
                String workflowNodeToId = currentNodeTrans.getWorkflowNodeToId();
                nextNode = findWorkflowNodeById(workflowNodeToId);
            }
        }
        //#endregion

        //#region过滤抄送节点及保存抄送记录
        if (null != nextNode && null != nextNode.getWorkflowNodeId()) {
            String workflowNodeType = nextNode.getWorkflowNodeType();
            switch (workflowNodeType) {
                case WorkflowConstant.NOTIFIER_NODE:
                    if (isSaveWorkflowLog) {
                        //region抄送节点,保存抄送信息并获取下一节点
                        Date date = new Date();
                        List<WorkflowApplyReviewLog> saveWorkflowTaskLogList = new ArrayList<>();
                        WorkflowApplyReviewLog workflowTaskLog = new WorkflowApplyReviewLog();
                        if ("1".equals(nextNode.getWorkflowNodeCheckType()) || "3".equals(nextNode.getWorkflowNodeCheckType()) || "4".equals(nextNode.getWorkflowNodeCheckType()) || "5".equals(nextNode.getWorkflowNodeCheckType())) {
                            //region抄送指定人员、角色、部门、自定义实现类
                            WorkflowNodeReview parCheckUser = new WorkflowNodeReview();
                            parCheckUser.setTenantId(tenantId);
                            parCheckUser.setWorkflowId(nextNode.getWorkflowId());
                            parCheckUser.setWorkflowNodeId(nextNode.getWorkflowNodeId());
                            parCheckUser.setWorkflowNodeCheckType(nextNode.getWorkflowNodeCheckType());
                            List<WorkflowNodeReview> nodeCheckUsers = workflowNodeReviewService.findWorkflowNodeReviews(parCheckUser);
                            if (null != nodeCheckUsers && nodeCheckUsers.size() > 0) {
                                for (WorkflowNodeReview nodeCheckUser : nodeCheckUsers) {
                                    String workflowNodeCheckType = nodeCheckUser.getWorkflowNodeCheckType();
                                    String workflowNodeCheckIds = nodeCheckUser.getWorkflowNodeCheckIds();
                                    if (StringUtils.isBlank(workflowNodeCheckIds) || StringUtils.isBlank(workflowNodeCheckType)) {
                                        continue;
                                    }
                                    switch (workflowNodeCheckType) {
                                        case "1":
                                            //#region 抄送指定人员
                                            User dbUser = userService.getById(workflowNodeCheckIds);
                                            if (null != dbUser) {
                                                workflowTaskLog = assembleNotifierByUser(workflowApplyId, tenantId, workflowId, nextNode.getWorkflowNodeId(), String.valueOf(dbUser.getUserId()), date);
                                                saveWorkflowTaskLogList.add(workflowTaskLog);
                                            }
                                            //#endregion
                                            break;
                                        case "3":
                                            //#region 抄送指定角色
                                            String roleId = workflowNodeCheckIds;
                                            //根据角色获取用户抄送
                                            List<User> userByRole = userService.findByRoleId(roleId, tenantId);
                                            if (null != userByRole && userByRole.size() > 0) {
                                                for (User sysUserRole : userByRole) {
                                                    workflowTaskLog = assembleNotifierByUser(workflowApplyId, tenantId, workflowId, nextNode.getWorkflowNodeId(), String.valueOf(sysUserRole.getUserId()), date);
                                                    saveWorkflowTaskLogList.add(workflowTaskLog);
                                                }
                                            }
                                            //#endregion
                                            break;
                                        case "4":
                                            //#region 抄送指定部门
                                            User userParam = new User();
                                            userParam.setTenantId(tenantId);
                                            userParam.setDeptId(workflowNodeCheckIds);
                                            List<User> userList = userService.findUserList(userParam);
                                            if (null != userList && userList.size() > 0) {
                                                for (User sysUser : userList) {
                                                    workflowTaskLog = assembleNotifierByUser(workflowApplyId, tenantId, workflowId, nextNode.getWorkflowNodeId(), String.valueOf(sysUser.getUserId()), date);
                                                    saveWorkflowTaskLogList.add(workflowTaskLog);
                                                }
                                            }
                                            //#endregion
                                            break;
                                        case "5":
                                            //#region 抄送自定义实现类
                                            saveWorkflowTaskLogList = assembleNotifierByCustom(workflowNodeCheckIds, workflowApplyId);
                                            //#endregion
                                            break;
                                        default:
                                            break;
                                    }

                                }
                            }
                            //endregion
                        } else if ("2".equals(nextNode.getWorkflowNodeCheckType())) {
                            //region抄送主管
                            User dbUser = userService.getById(createBy);
                            if (null != dbUser) {
                                User leaderByDeptId = userService.findLeaderByDeptId(dbUser.getDeptId());
                                if (null != leaderByDeptId) {
                                    workflowTaskLog = assembleNotifierByUser(workflowApplyId, tenantId, workflowId, nextNode.getWorkflowNodeId(), String.valueOf(leaderByDeptId.getUserId()), date);
                                    saveWorkflowTaskLogList.add(workflowTaskLog);
                                }
                            }
                            //endregion
                        } else if ("5".equals(nextNode.getWorkflowNodeCheckType())) {
                            //region抄送发起人自己
                            User dbUser = userService.getById(createBy);
                            if (null != dbUser) {
                                workflowTaskLog = assembleNotifierByUser(workflowApplyId, tenantId, workflowId, nextNode.getWorkflowNodeId(), String.valueOf(dbUser.getUserId()), date);
                                saveWorkflowTaskLogList.add(workflowTaskLog);
                            }
                            //endregion
                        }
                        //endregion
                        if (null != saveWorkflowTaskLogList && saveWorkflowTaskLogList.size() > 0) {
                            workflowApplyReviewLogService.saveBatch(saveWorkflowTaskLogList);
                        }
                    }
                    nextNode = getNextNode(nextNode, customizeBtnId, workflowApply, isSaveWorkflowLog);
                    break;
                case WorkflowConstant.ROUTE_NODE:
                case WorkflowConstant.CONDITION_NODE:
                    //条件父节点，继续获取下一条件节点
                    //条件节点，继续获取下一节点
                    nextNode = getNextNode(nextNode, customizeBtnId, workflowApply, isSaveWorkflowLog);
                    break;
                default:
                    break;
            }
        }
        return nextNode;
    }


    /**
     * 根据条件虚拟父节点route（条件）找到符合配置胡流向节点
     *
     * @param currentNodeTranList 当前条件节点所有条件流向
     * @param createBy            业务申请人
     * @param customizeBtnId          上一节点操作的按钮Id
     * @return
     */
    private WorkflowNode workflowConditionCompare(String workflowApplyId, List<WorkflowNodeTrans> currentNodeTranList, String createBy, String customizeBtnId) throws FebsException {
        WorkflowNode nextNode = new WorkflowNode();
        //region条件分支,根据条件获取流向
        for (WorkflowNodeTrans branchNodeTrans : currentNodeTranList) {
            boolean isConform = false;
            //流动条件;1：与或条件 2：并且条件
            String workflowNodeTransType = branchNodeTrans.getWorkflowNodeTransType();
            //#region 获取条件流向
            WorkflowNodeTransCondition parTransCondition = new WorkflowNodeTransCondition();
            parTransCondition.setTenantId(branchNodeTrans.getTenantId());
            parTransCondition.setWorkflowId(branchNodeTrans.getWorkflowId());
            parTransCondition.setWorkflowNodeTransId(branchNodeTrans.getWorkflowNodeTransId());
            List<WorkflowNodeTransCondition> workflowNodeTransConditions = workflowNodeTransConditionService.findWorkflowNodeTransConditions(parTransCondition);
            //#endregion
            if (null != workflowNodeTransConditions && workflowNodeTransConditions.size() > 0) {
                Integer workflowNodeTransConditionsLen = workflowNodeTransConditions.size();
                Integer sufficeConditionsLen = 0;
                for (WorkflowNodeTransCondition branchCondition : workflowNodeTransConditions) {
                    //条件类型1：发起人部门 2：发起人角色 3：审核操作（上一节点操作按钮）4：自定义（系统集成实现Class,返回true或者false）5：业务字段
                    String conditionType = branchCondition.getConditionType();
                    //业务表名
                    String businessTable = branchCondition.getBusinessTable();
                    //比较值 部门Id、角色Id、按钮Id、实现类名、字段名
                    String conditionKey = branchCondition.getConditionKey();
                    //比较公式 1：属于 2：不属于 3：大于 4：大于等于 5：小于 6：小于等于
                    String conditionOperation = branchCondition.getConditionOperation();
                    //比较值（设定value）
                    String conditionValue = branchCondition.getConditionValue();

                    if (StringUtils.isBlank(conditionType) || StringUtils.isBlank(conditionOperation)) {
                        continue;
                    }
                    switch (conditionType) {
                        case "1":
                            //#region条件 ：申请人部门
                            isConform = checkConditionByDept(conditionOperation, conditionKey, createBy);
                            //#endregion
                            break;
                        case "2":
                            //#region条件：申请人角色
                            isConform = checkConditionByRole(conditionOperation, conditionKey, createBy);
                            //#endregion
                            break;
                        case "3":
                            //#region条件:点击节点配置中的按钮
                            if (StringUtils.isNotBlank(customizeBtnId) && StringUtils.isNotBlank(conditionKey) && customizeBtnId.trim().equals(conditionKey.trim())) {
                                isConform = true;
                            }
                            //#endregion
                            break;
                        case "4":
                            //#region  条件：自定义实现类
                            try {
                                isConform = checkConditionByCustom(conditionKey, workflowApplyId);
                            } catch (Exception e) {
                                throw new FebsException("工作流程条件自定义匹配异常,请联系管理员");
                            }
                            //#endregion
                            break;
                        case "5":
                            //#region  条件：业务表字段值
                            isConform = checkConditionByForm(workflowApplyId, conditionOperation, businessTable, conditionKey, conditionValue);
                            //#endregion
                            break;
                        default:
                            break;

                    }
                    if ("1".equals(workflowNodeTransType)) {
                        //或
                        if (isConform) {
                            break;
                        }
                    } else {
                        //且
                        if (isConform) {
                            sufficeConditionsLen++;
                            if (workflowNodeTransConditionsLen.equals(sufficeConditionsLen)) {
                                break;
                            } else {
                                isConform = false;
                            }
                        }
                    }
                }
                if (isConform) {
                    //满足条件,返回流向节点
                    String workflowNodeToId = branchNodeTrans.getWorkflowNodeToId();
                    nextNode = findWorkflowNodeById(workflowNodeToId);
                    break;
                }
            }
        }
        //endregion
        return nextNode;
    }

    /**
     * 条件节点：申请人归属部门
     *
     * @param conditionOperation 比较公式 1：属于 2：不属于 3：大于 4：大于等于 5：小于 6：小于等于
     * @param conditionKey       部门Id
     * @param createBy           业务申请人userName
     * @return
     */
    private boolean checkConditionByDept(String conditionOperation, String conditionKey, String createBy) {
        boolean isConform = false;
        User basicUser = userService.findByName(createBy);
        String deptId = "";
        if (null != basicUser && null != basicUser.getDeptId()) {
            deptId = basicUser.getDeptId();
        }
        if ("1".equals(conditionOperation) && null != deptId && deptId.equals(conditionKey)) {
            isConform = true;
        }
        if ("2".equals(conditionOperation) && null != deptId && !deptId.equals(conditionKey)) {
            isConform = true;
        }
        return isConform;
    }

    /**
     * 条件节点：申请人归属角色
     *
     * @param conditionOperation 比较公式 1：属于 2：不属于 3：大于 4：大于等于 5：小于 6：小于等于
     * @param conditionKey       角色Id
     * @param createBy           业务申请人userName
     * @return
     */
    private boolean checkConditionByRole(String conditionOperation, String conditionKey, String createBy) {
        boolean isConform = false;
        List<Role> sysUserRoleList = roleService.findUserRole(createBy);
        Role sysRole = new Role();
        if (null != sysUserRoleList && sysUserRoleList.size() > 0) {
            sysRole = sysUserRoleList.stream().filter(p -> p.getRoleId().equals(conditionKey.trim())).findFirst().orElse(null);
        }
        if ("1".equals(conditionOperation) && null != sysRole && null != sysRole.getRoleId()) {
            isConform = true;
        }
        if ("2".equals(conditionOperation) && null == sysRole) {
            isConform = true;
        }
        return isConform;
    }

    /**
     * 条件节点：自定义实现类
     *
     * @param customClass     自定义实现类名
     * @param workflowApplyId 业务申请Id
     * @return
     */
    private boolean checkConditionByCustom(String customClass, String workflowApplyId) {
        boolean isConform = false;
        try {
            Object[] args = new Object[]{workflowApplyId};
            Class<?>[] argsType = new Class<?>[]{String.class};
            Class<?> clazz = SpringContextUtil.getType(customClass);
            Object instance = clazz.newInstance();
            Method method = clazz.getMethod("execute", argsType);
            Object result = method.invoke(instance, args);
            if (result instanceof Boolean) {
                isConform = (Boolean) result;
            }
        } catch (Exception ex) {
            log.error("工作流程自定义条件匹配实现异常，自定义执行类：【" + customClass + "】,入参：【" + workflowApplyId + "】，错误信息：" + ex.getMessage());
        }
        return isConform;
    }

    /**
     * 条件节点：业务字段
     *
     * @param conditionOperation 比较公式 1：属于 2：不属于 3：大于 4：大于等于 5：小于 6：小于等于
     * @param businessTable      业务表名
     * @param conditionKey       业务表名字段
     * @param conditionValue     与业务数据比较值
     * @return
     */
    private boolean checkConditionByForm(String workflowApplyId, String conditionOperation, String businessTable, String conditionKey, String conditionValue) {
        boolean isConform = false;
        //TODO 业务字段比较
        return isConform;
    }

    /**
     * 抄送节点：组装抄送信息
     *
     * @param workflowId
     * @return
     */
    private WorkflowApplyReviewLog assembleNotifierByUser(String workflowApplyId, String tenantId, String workflowId, String workflowNodeId, String userName, Date date) {
        WorkflowApplyReviewLog workflowApplyReviewLog = new WorkflowApplyReviewLog();

        workflowApplyReviewLog = new WorkflowApplyReviewLog();
        workflowApplyReviewLog.setWorkflowApplyId(workflowApplyId);
        workflowApplyReviewLog.setTenantId(tenantId);
        workflowApplyReviewLog.setWorkflowId(workflowId);
        workflowApplyReviewLog.setWorkflowNodeId(workflowNodeId);
        workflowApplyReviewLog.setWorkflowNodeType("2");
        workflowApplyReviewLog.setReviewUserType("1");
        workflowApplyReviewLog.setReviewDate(date);
        workflowApplyReviewLog.setUserId(userName);
        workflowApplyReviewLog.setReadable("1");
        workflowApplyReviewLog.setCreatedBy("system");
        workflowApplyReviewLog.setCreatedTime(date);
        return workflowApplyReviewLog;
    }

    /**
     * 抄送节点：自定义实现类
     *
     * @param customClass     自定义实现类名
     * @param workflowApplyId 业务申请Id
     * @return
     */
    private List<WorkflowApplyReviewLog> assembleNotifierByCustom(String customClass, String workflowApplyId) {
        List<WorkflowApplyReviewLog> applyReviewLogList = new ArrayList<>();
        try {
            Object[] args = new Object[]{workflowApplyId};
            Class<?>[] argsType = new Class<?>[]{String.class};
            Class<?> clazz = SpringContextUtil.getType(customClass);
            Object instance = clazz.newInstance();
            Method method = clazz.getMethod("execute", argsType);
            Object result = method.invoke(instance, args);
            //TODO 解析 result 转化为 WorkflowApplyReviewLog


        } catch (Exception ex) {
            log.error("工作流程自定义抄送实现异常，自定义执行类：【" + customClass + "】,入参：【" + workflowApplyId + "】，错误信息：" + ex.getMessage());
        }
        return applyReviewLogList;
    }

    @Override
    public List<Map<String, String>> queryWorkflowTableColums(String name) {
        List<String> notInList = new ArrayList<>();
        notInList.add("accident_no");
        notInList.add("accident_type");
        notInList.add("accident_title");
        notInList.add("accident_date");
        notInList.add("accident_area_name");
        notInList.add("created_by");
        notInList.add("created_time");
        notInList.add("updated_by");
        notInList.add("updated_time");
        notInList.add("deleted_by");
        notInList.add("deleted_time");
        notInList.add("deleted_flg");
        return baseMapper.queryWorkflowTableColums(name, notInList);
    }

    @Override
    public List<Map<String, String>> selectTable() {
        return baseMapper.selectTable();
    }

}
